package interaction

import (
	"time"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/interactiond"

	"github.com/gin-gonic/gin"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/base"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/sysparam"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/groupd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
)

func createCtrl(d core.CmsDomain) *interactionCtrl {
	return &interactionCtrl{
		BaseContrl: base.BaseContrl{
			Domain: d,
		},
		info: d.Info(),
		rar:  d.Interaction().ReplayAggregateRoot(),
		igar: d.Interaction().GroupAggregateRoot(),
		tar:  d.Interaction().TypeAggregateRoot(),
		iiar: d.Interaction().InteractionAggregateRoot(),
		iar:  d.Info().InfoAggregateRoot(),
		car:  d.Column().ColumnAggregateRoot(),
		gar:  d.Group().GroupAggregateRoot(),
	}
}

type interactionCtrl struct {
	base.BaseContrl
	info infod.InfoDomain
	iar  infod.InfoAggregateRoot
	car  columnd.ColumnAggregateRoot
	gar  groupd.GroupAggregateRoot
	rar  interactiond.ReplayAggregateRoot
	igar interactiond.GroupAggregateRoot
	tar  interactiond.TypeAggregateRoot
	iiar interactiond.InteractionAggregateRoot
}

// // InfoSearch 查询条件
// type InfoSearch struct {
// 	// UID OrgID 如果都为空 :
// 	// 	 Range 0 查询所有信息包含 所有者和所属组织的信息
// 	// 	Range  1 查询除所属组织所属用户以外的信息
// 	// UID OrgID 任何一个不为空：
// 	// 	  Range 参数失效
// 	Range    int      `from:"range"`
// 	UID      string   `from:"owner"`  // 所有者用户编号
// 	OrgID    string   `from:"org"`    // 组织编号
// 	ColumnID string   `from:"column"` // 栏目编号
// 	Key      string   `from:"key"`    // 关键字
// 	Tags     []string `from:"tags"`   //  匹配标签

// }
// type reqReplay struct {
// 	TargetType interactiond.IGTargetType `json:"target_type" bind:"required"`
// 	TargetID   string                    `json:"target_id" bind:"required"`
// 	ParentID   string                    `json:"parent_id"`
// 	Content    string                    `json:"content" bind:"required,max=1000"`
// }

// func (c interactionCtrl) replay(ctx *gin.Context) {
// 	var req reqReplay

// 	if err := ctx.BindJSON(&req); err != nil {
// 		c.ErrBadRequestByBind(ctx, 1, err)
// 		return
// 	}
// 	dctx := c.DDDContext(ctx)
// 	if dctx.UID() == "" {
// 		c.ErrUnauthorized(ctx, "保存失败：未登录")
// 		return
// 	}
// 	if req.ParentID != "" {
// 		if p, err := c.rar.GetReplay(dctx, req.ParentID); err != nil || p == nil {
// 			c.ErrBadRequest(ctx, 2, "上级评论不存在或查询失败", err)
// 			return
// 		}
// 	}
// 	// 检查评论目标主体是否存在
// 	ga, err := factory.DefaultFactory.GetOrCreIGroup(dctx, req.TargetType, req.TargetID)

// 	//ga, err := c.igar.GetIGroup2(dctx, req.TargetType, req.TargetID)
// 	if err != nil {
// 		c.ErrBadRequest(ctx, 2, "禁止评论", err)
// 		return
// 	}
// 	if ga.IsReplay == 0 {
// 		c.ErrForbidden(ctx, "禁止评论", err)
// 		return
// 	}
// 	igid := ga.IGID

// 	rs := interactiond.RStatusNormal
// 	if ga.IsReplayChk == 1 {
// 		rs = interactiond.RStatusWaitChk
// 	}

// 	id, err := c.rar.Replay(dctx, interactiond.ReplayPath{
// 		IGID:     igid,
// 		ParentID: req.ParentID,
// 	}, interactiond.ReplayDesc{
// 		Context: req.Content,
// 		Status:  rs,
// 	})
// 	if err != nil {
// 		c.ErrServerError(ctx, 5, "创建评论失败", err)
// 		return
// 	}
// 	c.Success(ctx, map[string]interface{}{"replay_id": id})
// }

type respReplay struct {
	ReplayID string    `json:"replay_id"`
	ParentID string    `json:"parent_id"`
	Content  string    `json:"content"`
	ChildNum int       `json:"child_num"`
	Creator  string    `json:"creator"`
	CreTime  time.Time `json:"cre_time"`
	MyLike   bool      `json:"my_like"`
	LikeNum  int       `json:"like_num"`
}

func toRespReplay(r *interactiond.ReplayAggregate) *respReplay {
	return &respReplay{
		ReplayID: r.ReplayID,
		ParentID: r.ParentID,
		Content:  r.Context,
		ChildNum: r.ReplayNum,
		Creator:  r.Creator,
		CreTime:  r.CreTime,
		LikeNum:  r.LikeNum,
	}
}

func (c interactionCtrl) toRespReplays(ctx ddd.Context, r []interactiond.ReplayAggregate) (out []*respReplay) {
	intTypeLikeCode := sysparam.IntsLikeCode()
	out = make([]*respReplay, 0, len(r))
	ov := make(map[string]*respReplay)
	igids := make([]string, 0, len(r))
	for _, v := range r {
		tmp := toRespReplay(&v)
		out = append(out, tmp)
		igid := c.igar.ID(interactiond.IGTTReplay, tmp.ReplayID)
		ov[igid] = tmp
		igids = append(igids, igid)
	}
	uid := ctx.UID()
	if uid != "" && len(igids) > 0 {
		if _, is, err := c.iiar.QueryPage(ctx, interactiond.InteractionSearch{
			IGID:  igids,
			UID:   []string{uid},
			Codes: []string{intTypeLikeCode},
		}, common.PageInfo{PageSize: len(igids)}); err != nil {
			log.Warnf("查询我点赞的内容失败")
			return
		} else if len(is) > 0 {
			for _, v := range is {
				ov[v.IGID].MyLike = true
			}
		}
	}
	return
}
func (c interactionCtrl) replayHostPageList(ctx *gin.Context) {

	igid := ctx.Param("igid")
	if igid == "" {
		c.ErrBadRequest(ctx, 1, "组ｉｄ没有设置")
		return
	}
	dctx := c.DDDContext(ctx)

	g, err := c.igar.GetGroup(dctx, igid)
	if err != nil {
		c.ErrServerError(ctx, 2, "查询失败", err)
		return
	}
	if g == nil || g.ReplayNum < 10 {
		c.Success(ctx, []string{})
		return
	}

	cs, err := c.rar.QueryGroupHostReplayPage(dctx, igid)
	if err != nil {
		c.ErrServerError(ctx, 3, "查询失败", err)
		return
	}

	c.Success(ctx, c.toRespReplays(dctx, cs))
}
func (c interactionCtrl) replayFirstPageList(ctx *gin.Context) {

	igid := ctx.Param("igid")
	if igid == "" {
		c.ErrBadRequest(ctx, 1, "组ｉｄ没有设置")
		return
	}
	pi := c.GetPageInfo(ctx, common.PageModeID)
	dctx := c.DDDContext(ctx)
	pr, cs, err := c.rar.QueryGroupReplayPage(dctx, igid, []interactiond.RStatus{interactiond.RStatusNormal}, pi)
	if err != nil {
		c.ErrServerError(ctx, 2, "查询失败", err)
		return
	}

	c.SuccessPage(ctx, pi, pr, c.toRespReplays(dctx, cs))
}
func (c interactionCtrl) queryReplayByID(ctx *gin.Context) {

	replayid := ctx.Param("replayid")
	if replayid == "" {
		c.ErrBadRequest(ctx, 1, "没有设置评论编号")
		return
	}
	dctx := c.DDDContext(ctx)
	ri, err := c.rar.GetReplay(dctx, replayid)
	if err != nil {
		c.ErrServerError(ctx, 2, "查询失败", err)
		return
	}
	rp := toRespReplay(ri)
	c.Success(ctx, rp)
}
func (c interactionCtrl) replayChildrenPageList(ctx *gin.Context) {

	parentid := ctx.Param("parentid")
	if parentid == "" {
		c.ErrBadRequest(ctx, 1, "上级id没有设置")
		return
	}
	pi := c.GetPageInfo(ctx, common.PageModeID)
	dctx := c.DDDContext(ctx)
	replay, err := c.rar.GetReplay(dctx, parentid)
	if err != nil {
		c.ErrBadRequest(ctx, 2, "指定的回复不存在或查询失败.", err)
		return
	}
	pr, cs, err := replay.QueryChildrenPage(dctx, pi)
	if err != nil {
		c.ErrServerError(ctx, 2, "查询失败", err)
		return
	}

	c.SuccessPage(ctx, pi, pr, c.toRespReplays(dctx, cs))
}

type responsGroupInfo struct {
	IGID         string    `json:"igid"`
	LastTime     time.Time `json:"last_time"`     // 子评论最后评论时间
	LastReplayer string    `json:"last_replayer"` // 子评论最后评论人
	Totals       infoTotal `json:"totals"`
}

func (c interactionCtrl) getGroupinfo(ctx *gin.Context) {

	igid := ctx.Param("igid")
	if igid == "" {
		c.ErrBadRequest(ctx, 1, "互动组ｉｄ没有设置")
		return
	}
	dctx := c.DDDContext(ctx)
	g, err := c.igar.GetGroup(dctx, igid)
	if err != nil {
		c.ErrBadRequest(ctx, 2, "查询失败.", err)
		return
	}
	if g == nil {
		c.Success(ctx, responsGroupInfo{IGID: igid})
		return
	}
	igt := infoTotal{
		ReplayNum: g.ReplayNum,
	}
	intTypeLikeCode := sysparam.IntsLikeCode()
	intTypeCollCode := sysparam.IntsCollectionCode()

	for _, v := range g.GroupTotal {
		switch v.ITCode {
		case intTypeLikeCode:
			igt.LikeNum = v.Total
		case intTypeCollCode:
			igt.CollNum = v.Total
		default:
		}
	}
	r := responsGroupInfo{
		IGID:         g.IGID,
		LastTime:     g.LastTime,
		LastReplayer: g.LastReplayer,
		Totals:       igt,
	}
	c.Success(ctx, r)
}
